package com.timothy.fund.data;

import android.content.Context;
import android.content.res.XmlResourceParser;
import com.timothy.fund.bean.Repo;
import com.timothy.fund.ui.R;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
<repo>
 <index>1</index>
 <type>1</type>
 <code>sh204001</code>
 <name>GC001</name>
</repo>
 
 */
public class ParseXML {
 
    public static List<Repo> getRepoList(Context context) {
        List<Repo> rList = new ArrayList<Repo>();
        XmlResourceParser xrp = context.getResources().getXml(R.xml.repos);
        try {
            // 还没有到XML文档的结尾处
            Repo repo = null;
            while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
                if (xrp.getEventType() == XmlResourceParser.START_TAG) {
                    String tagName = xrp.getName();
                    if (tagName.equals("repo")) {
                        repo = new Repo();
                    }
                    if(tagName.equals("index") && repo !=null){
                        repo.setIndex(Integer.valueOf(xrp.nextText()));
                    }
                    if(tagName.equals("type") && repo !=null){
                        repo.setType(Integer.valueOf(xrp.nextText()));
                    }
                    if(tagName.equals("code") && repo !=null){
                        repo.setCode(xrp.nextText());
                    }
                    if(tagName.equals("name") && repo !=null){
                        repo.setName(xrp.nextText());
                    }
                }
                if(xrp.getEventType() == XmlResourceParser.END_TAG){
                    String tagName = xrp.getName();
                    if (tagName.equals("repo")) {
                        rList.add(repo);
                    }
                }
                xrp.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rList;
    }

    public static List<String> getRepoCodeList(Context context) {
        List<String> rList = new ArrayList<String>();
        XmlResourceParser xrp = context.getResources().getXml(R.xml.repos);
        try {
            // 还没有到XML文档的结尾处
            while (xrp.getEventType() != XmlResourceParser.END_DOCUMENT) {
                if (xrp.getEventType() == XmlResourceParser.START_TAG) {
                    String tagName = xrp.getName();
                    if(tagName.equals("code")){
                        rList.add(xrp.nextText().toString());
                    }
                }
                xrp.next();
            }
        } catch (XmlPullParserException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return rList;
    }
}

